﻿using System;
using System.Data;
using System.Data.SqlClient;
using TMDT.BusinessObjects;

namespace TMDT.BusinessLogic
{
    public static class BusinessHelper
    {
        public static string ConnectionString
        {
            get { return "Data Source=.;Initial Catalog=TMDT;Integrated Security=true;"; }
        }
        private static SqlConnection c = new SqlConnection(ConnectionString);

        private static void MoKetNoi()
        {
            if (c.State != ConnectionState.Open)
            {
                c.Open();
            }
        }

        private static void DongKetNoi()
        {
            if (c.State == ConnectionState.Open)
            {
                c.Close();
            }
        }

        public static bool CapNhatDuLieu(Command cm)
        {
            bool bKQ = true;
            try
            {
                MoKetNoi();
                SqlCommand command = new SqlCommand(cm.CommandText,c);
                command.CommandType = cm.CommandType;
                command.Parameters.AddRange(cm.Parameter);
                command.ExecuteNonQuery();

            }
            catch
            {
                bKQ = false;
            }
            finally
            {
                DongKetNoi();
            }
            return bKQ;
        }

        public static DataSet TruyVanDuLieu(Command cm)
        {
            DataSet dataSet = new DataSet();
            try
            {
                MoKetNoi();
                SqlCommand command = new SqlCommand(cm.CommandText,c);
                command.CommandType = command.CommandType;
                if(cm.Parameter != null)
                {
                    command.Parameters.AddRange(cm.Parameter);
                }
                SqlDataAdapter adapter = new SqlDataAdapter(command);
                adapter.Fill(dataSet);
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
            finally
            {
                DongKetNoi();
            }
            return dataSet;
        }
    }
}
